<template>
  <div>
    <!-- 面包屑部分 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片部分 -->
    <el-card shadow="always">
      <!-- 搜索框部分 -->
      <div style="margin-top: 10px">
        <el-row :gutter="20">
          <el-col :span="10">
            <div class="grid-content bg-purple">
              <el-input
                placeholder="请输入用户"
                class="input-with-select"
                v-model="queryInfo.query"
                @blur="loseFocus($event)"
                @clear="getUsers"
                clearable
              >
                <el-button
                  slot="append"
                  icon="el-icon-search"
                  @click="search"
                ></el-button>
              </el-input>
            </div>
          </el-col>
          <el-col :span="2">
            <div class="grid-content bg-purple">
              <el-button type="primary" @click="changePopup">
                添加用户
              </el-button>
            </div>
          </el-col>
        </el-row>
      </div>
      <el-divider></el-divider>
      <!-- 内容部分 -->
      <div>
        <el-table :data="userlist" border stripe>
          <el-table-column type="index" label="#"> </el-table-column>
          <el-table-column prop="username" label="用户名"> </el-table-column>
          <el-table-column prop="email" label="邮箱"> </el-table-column>
          <el-table-column prop="mobile" label="电话"></el-table-column>
          <el-table-column prop="role_name" label="角色"> </el-table-column>
          <el-table-column label="状态">
            <template slot-scope="scope">
              <el-switch
                @change="updateState(scope.row)"
                v-model="scope.row.mg_state"
                active-color="#13ce66"
                inactive-color="#ff4949"
              >
              </el-switch>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="180">
            <template slot-scope="scope">
              <el-button
                @click="editUser(scope.row.id)"
                type="primary"
                icon="el-icon-edit"
                size="mini"
              ></el-button>
              <el-button
                type="danger"
                @click="deleteUser(scope.row.id)"
                icon="el-icon-delete"
                size="mini"
              ></el-button>
              <el-tooltip
                effect="light"
                :enterable="false"
                content="分配角色"
                placement="top"
              >
                <el-button
                  @click="setRoles(scope.row)"
                  type="warning"
                  icon="el-icon-setting"
                  size="mini"
                ></el-button>
              </el-tooltip>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div class="page">
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="queryInfo.pagenum"
          :page-sizes="[1, 2, 3, 4]"
          :page-size="queryInfo.pagesize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
        >
        </el-pagination>
      </div>
    </el-card>
    <!-- 弹出框区域 -->
    <!-- 添加用户弹出 -->
    <el-dialog
      :close-on-click-modal="false"
      :before-close="handleClose"
      @close="resetOne"
      title="添加用户"
      :visible="isPopup"
      width="50%"
    >
      <el-form
        :model="addFrom"
        :rules="addFromRules"
        ref="addFormRef"
        label-width="80px"
      >
        <el-form-item label="用户名" prop="username">
          <el-input v-model="addFrom.username"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password" type="password">
          <el-input v-model="addFrom.password"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="addFrom.email"></el-input>
        </el-form-item>
        <el-form-item label="电话号码" prop="mobile">
          <el-input v-model="addFrom.mobile"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="isPopup = false">取 消</el-button>
        <el-button type="primary" @click="addUser"> 确 定 </el-button>
      </span>
    </el-dialog>
    <!-- 修改用户弹出 -->
    <el-dialog
      title="修改用户信息"
      @close="resetTwo"
      :visible.sync="isEdit"
      width="50%"
    >
      <el-form
        :model="editFrom"
        :close-on-click-modal="false"
        :rules="editFromRules"
        ref="editFromRef"
        label-width="80px"
      >
        <el-form-item label="用户名">
          <el-input v-model="editFrom.username" :disabled="true"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="editFrom.email"></el-input>
        </el-form-item>
        <el-form-item label="电话号码" prop="mobile">
          <el-input v-model="editFrom.mobile"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="isEdit = false">取 消</el-button>
        <el-button type="primary" @click="edit(editFrom.id)">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 分配角色弹出框 -->
    <el-dialog
      @close="resetThree"
      title="分配角色"
      :visible.sync="isSetRoles"
      width="50%"
    >
      <p>当前用户名：{{ this.usersinfo.username }}</p>
      <p>当前角色：{{ this.usersinfo.role_name }}</p>
      <p>
        当前角色：
        <el-select v-model="setRolesid" placeholder="请选择角色">
          <el-option
            v-for="item in RolesList"
            :key="item.id"
            :label="item.roleName"
            :value="item.id"
          >
          </el-option>
        </el-select>
      </p>

      <span slot="footer" class="dialog-footer">
        <el-button @click="isSetRoles = false">取 消</el-button>
        <el-button type="primary" @click="entRoles">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: 'Users',
  data() {
    //自定义规则
    var checkEmail = (rule, value, cb) => {
      var reg = /^([a-zA-Z]|[0-9])(\w|\-)+@[a-zA-Z0-9]+\.([a-zA-Z]{2,4})$/;
      if (reg.test(value)) {
        return cb()
      }
      cb(new Error('请输入合法邮箱!!'))
    };
    var checkMobile = (rule, value, cb) => {
      let reg = /^(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\d{8}$/
      if (reg.test(value)) {
        return cb()
      }
      cb(new Error('请输入合法电话号码!!'))
    };
    return {
      //parmas参数
      queryInfo: {
        query: '',
        pagenum: 1,
        pagesize: 4
      },
      userlist: [],
      //用户信息总数
      total: 0,
      //是否弹出用户添加
      isPopup: false,
      // 是否弹出用户修改
      isEdit: false,
      // 是否弹出分配角色
      isSetRoles: false,
      // 所分配角色信息
      usersinfo: {},
      // 角色列表
      RolesList: [],
      // 表单数据
      addFrom: {
        username: '',
        password: '',
        email: '',
        mobile: ''
      },
      // 所选角色的id值
      setRolesid: '',
      // 修改表单数据
      editFrom: {},
      // 表单规则
      addFromRules: {
        username:
          [
            { required: true, message: '请输入用户名', trigger: 'blur' },
            { min: 3, max: 6, message: '长度在 3 到 6 个字符', trigger: 'blur' }
          ],
        password:
          [
            { required: true, message: '请输入密码', trigger: 'blur' },
            { min: 6, max: 12, message: '长度在 6 到 12 个字符', trigger: 'blur' }
          ],
        email:
          [
            { required: true, message: '请输入邮箱', trigger: 'blur' },
            { validator: checkEmail, trigger: 'blur' },
          ],
        mobile:
          [
            { required: true, message: '请输入电话号码', trigger: 'blur' },
            { validator: checkMobile, trigger: 'blur' },

          ],
      },
      // 修改表单规则
      editFromRules: {
        email:
          [
            { required: true, message: '请输入邮箱', trigger: 'blur' },
            { validator: checkEmail, trigger: 'blur' },
          ],
        mobile:
          [
            { required: true, message: '请输入电话号码', trigger: 'blur' },
            { validator: checkMobile, trigger: 'blur' },

          ],
      }

    }
  },
  created() {
    this.getUsers()
  },
  methods: {
    getUsers() {
      this.$http.get("http://127.0.0.1:8888/api/private/v1/users", { params: this.queryInfo })
        .then((response) => {

          if (response.data.meta.status !== 200) {
            this.$message.error(response.data.meta.msg);
          } else {
            this.userlist = response.data.data.users;
            this.total = response.data.data.total
          }
        })
        .catch((error) => console.log(error));

    },
    // 输入框为空时数据变回未搜索之前
    loseFocus(e) {
      if (!e.target.value) {
        this.getUsers()
      }
      this.search()
    },
    //更新当前页数存放的信息条数
    handleSizeChange(value) {
      this.queryInfo.pagesize = value
      this.getUsers()
    },
    // 更新当前页数
    handleCurrentChange(value) {
      this.queryInfo.pagenum = value
      this.getUsers()
    },
    search() {
      //当搜索时页面从大变小时数据显示不出
      if (this.queryInfo.pagenum >= Math.ceil(this.total / this.queryInfo.pagesize)) {
        this.queryInfo.pagenum = Math.ceil(this.total / this.queryInfo.pagesize)
        this.getUsers()
      } else {
        this.getUsers()
      }

    },
    // 状态开关监听更改事件
    updateState(stateinfo) {
      this.$http.put(`http://127.0.0.1:8888/api/private/v1/users/${stateinfo.id}/state/${stateinfo.mg_state}`)
        .then((response) => {
          if (response.data.meta.status !== 200) {
            stateinfo.mg_state = !stateinfo.mg_state
            this.$message.error(response.data.meta.msg);
          } else {
            this.$message.success(response.data.meta.msg);
          }
        }).catch((err) => {
          console.log(error)
        });
    },
    // 控制添加用户弹窗弹出
    changePopup() {
      this.isPopup = true
    },
    // 通过×控制添加用户弹窗关闭
    handleClose() {
      this.isPopup = false
    },
    // 重置表单
    resetOne() {
      this.$refs.addFormRef.resetFields()
    },
    resetTwo() {
      this.$refs.editFromRef.resetFields()
    },
    resetThree() {
      this.setRolesid = ''
      this.usersinfo = {}

    },
    // 添加用户
    addUser() {
      this.$refs.addFormRef.validate((value) => {
        if (!value) {
          this.$message.error('请完整的输入合法信息！！！')
        } else {
          this.$http.post('http://127.0.0.1:8888/api/private/v1/users', this.addFrom)
            .then((response) => {
              if (response.data.meta.status !== 201) {
                this.$message.error(response.data.meta.msg);
              } else {
                this.$message.success('用户添加成功');
                this.isPopup = false
                this.getUsers()
              }
            }).catch((err) => console.log(err))
        }

      })
    },
    // 修改用户信息是信息默认显示
    editUser(id) {
      this.isEdit = true
      this.$http.get(`http://127.0.0.1:8888/api/private/v1/users/${id}`)
        .then((response) => {
          if (response.data.meta.status !== 200) {
            this.$message.error(response.data.meta.msg);
          } else {
            this.editFrom = response.data.data

          }
        })
        .catch((error) => console.log(error));

    },
    // 确认修改
    edit(id) {
      this.$refs.editFromRef.validate((value) => {
        if (!value) {
          this.$message.error('请完整的输入合法信息！！！')
        } else {
          this.$http.put(`http://127.0.0.1:8888/api/private/v1/users/${id}`,
            { email: this.editFrom.email, mobile: this.editFrom.mobile })
            .then((response) => {
              if (response.data.meta.status !== 200) {
                this.$message.error(response.data.meta.msg);
              } else {
                this.$message.success('用户修改成功');
                this.isEdit = false
                this.getUsers()
              }
            }).catch((err) => console.log(err))
        }
      })
    },
    //删除用户
    deleteUser(id) {
      this.$confirm('此操作将永久删除该用户, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.$http.delete(`http://127.0.0.1:8888/api/private/v1/users/${id}`)
          .then((response) => {
            if (response.data.meta.status !== 200) {
              this.$message.error(response.data.meta.msg);
            } else {
              this.$message.success(response.data.meta.msg);
              this.getUsers()
            }
          }).catch((error) => console.log(error))
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });



    },
    //分配角色
    setRoles(role) {
      this.usersinfo = role
      console.log(this.usersinfo);
      this.$http.get('http://127.0.0.1:8888/api/private/v1/roles')
        .then((response) => {
          if (response.data.meta.status !== 200) {
            this.$message.error(response.data.meta.msg);
          } else {
            this.RolesList = response.data.data;
          }
        }).catch((error) => console.log(error))

      this.isSetRoles = true
    },
    entRoles() {
      if (!this.setRolesid) {
        return this.$message.error('请选择要分配的角色！')
      }
      this.$http.put(`http://127.0.0.1:8888/api/private/v1/users/${this.usersinfo.id}/role`,
        { rid: this.setRolesid })
        .then((response) => {
          if (response.data.meta.status !== 200) {
            this.$message.error(response.data.meta.msg);
          } else {
            this.$message.success(response.data.meta.msg);
            this.getUsers()
          }
        }).catch((error) => console.log(error))

      this.isSetRoles = false
    },

  }
}
</script>

<style>
.el-card {
  margin-top: 20px;
}
</style>